package cn.edu.zafu.bigdata.zengyadian;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        try {
            // 创建UDP套接字，监听指定端口（这里假设为8888，可根据需要修改）
            DatagramSocket serverSocket = new DatagramSocket(8888);
            System.out.println("UDP服务端已启动，等待客户端请求...");

            while (true) {
                // 准备接收客户端请求的数据包
                byte[] buffer = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
                serverSocket.receive(receivePacket);

                // 获取客户端的地址和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前服务器时间
                Date now = new Date();
                String timeString = now.toString();
                byte[] timeData = timeString.getBytes();

                // 准备发送给客户端的数据包
                DatagramPacket sendPacket = new DatagramPacket(timeData, timeData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);

                System.out.println("已向客户端发送当前时间：" + timeString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

